import java.util.Arrays;

public class CanPartition {

    public boolean canPartition1(int[] nums) {
        int sum = 0;
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            sum += nums[i];
        }
        if (sum % 2 != 0) return false;
        int[][] dp = new int[n + 1][sum / 2 + 1];
        dp[n][0] = 1;
        for (int i = n - 1; i >= 0; i--) {
            for (int j = 0; j <= sum / 2; j++) {
                if (j - nums[i] >= 0) {
                    dp[i][j] = Math.max(dp[i + 1][j], dp[i + 1][j - nums[i]]);
                } else {
                    dp[i][j] = dp[i + 1][j];
                }
            }
        }
        return dp[0][sum / 2] == 1;
    }

    public boolean canPartition(int[] nums) {
        int sum = Arrays.stream(nums).sum();
        if (sum % 2 != 0) return false;
        int m = sum / 2;
        boolean[] dp = new boolean[m + 1];
        dp[0] = true;
        for (int num : nums) {
            for (int i = m; i >= num; i--) {
                dp[i] = dp[i] || dp[i - num];
            }
        }
        return dp[m];
    }
}
